package com.lht.syt.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lht.syt.cmn.listener.DictListener;
import com.lht.syt.cmn.mapper.DictMapper;
import com.lht.syt.cmn.service.DictService;
import com.lht.syt.model.cmn.Dict;
import com.lht.syt.vo.cmn.DictEeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> dictList = this.dictMapper.selectList(queryWrapper);

        // 循环查询效率太低
//        for (Dict dict:dictList) {
//            Long dictId = dict.getId();
//            boolean isChild = this.isChildren(dictId);
//            dict.setHasChildren(isChild);
//        }
        if (0 != dictList.size()) {
            // 收集ids一次性查询下级
            Set<Long> childIds = dictList.stream().map(Dict::getId).collect(Collectors.toSet());
            QueryWrapper<Dict> countWrapper = new QueryWrapper<>();
            countWrapper.in("parent_id", childIds);
            List<Dict> childDictList = this.dictMapper.selectList(countWrapper);

            // Collectors.groupingBy：这是一个收集器（Collector），用于根据某个分类函数（classifier function）对元素进行分组。在这里，分类函数是Dict::getParentId，即根据Dict对象的parentId属性进行分组。
            // Dict::getParentId：这是一个方法引用，表示我们使用Dict对象的getParentId方法作为分组依据。
            // Collectors.counting()：这是另一个收集器，用于计算每个分组中元素的数量。
            Map<Long, Long> childMap = childDictList.stream().collect(Collectors.groupingBy(Dict::getParentId, Collectors.counting()));

            // 设置hasChildren属性
            for (Dict dict : dictList) {
                Long dictId = dict.getId();
                boolean isChild = childMap.getOrDefault(dictId, 0L) > 0;
                dict.setHasChildren(isChild);
            }
        }

        return dictList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        // 当数据量很大时，可以考虑： 1.分页查询写入  2.流式 API
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            List<Dict> dictList = this.dictMapper.selectList(null);
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());  // 转化bean，去除不必要字段
            for(Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictVo);
                dictVoList.add(dictVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
        } catch (IOException e) {  // UnsupportedEncodingException
            e.printStackTrace();
        }
    }

    //导入数据字典
    @Override
    @CacheEvict(value = "dict", allEntries=true)  // 导入后清理所有缓存
    public void importDictData(MultipartFile file) {
        try {
            // 传入字典监听器，按行读取
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        if(StringUtils.isEmpty(parentDictCode)) {
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        } else {
            Dict parentDict = this.getByDictCode(parentDictCode);
            if(null == parentDict) return "";
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parentDict.getId()).eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        }
        return "";
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict codeDict = this.getByDictCode(dictCode);
        if(null == codeDict) return null;
        return this.findChildData(codeDict.getId());
    }

    private Dict getByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }
    //判断id下面是否有子节点

    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        // 0>0    1>0
        return count>0;
    }

}
